/***
 * Copyright (c) 2010 readyState Software Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package it.unina.lab.anm.ui;

import it.unina.lab.anm.R;
import it.unina.lab.anm.TTS;
import it.unina.lab.anm.dao.AnmServiceException;
import it.unina.lab.anm.dao.AnmServices;
import it.unina.lab.anm.dao.DatabaseService;
import it.unina.lab.anm.models.PrevisioniPalina;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.maps.OverlayItem;

/**
 * A view representing a MapView marker information balloon.
 * <p>
 * This class has a number of Android resource dependencies:
 * <ul>
 * <li>drawable/balloon_overlay_bg_selector.xml</li>
 * <li>drawable/balloon_overlay_close.png</li>
 * <li>drawable/balloon_overlay_focused.9.png</li>
 * <li>drawable/balloon_overlay_unfocused.9.png</li>
 * <li>layout/balloon_map_overlay.xml</li>
 * </ul>
 * </p>
 * 
 * @author Jeff Gilfelt
 *
 */
public class BalloonOverlayView<Item extends OverlayItem> extends FrameLayout {

	private LinearLayout layout;
	private TextView title;
	private TextView snippet;
	private CheckBox star_check;
	private ImageView speaker_button;
	private DatabaseService mDB;
	private Handler UIhandler = null;
	
	private String errorMessage;
	private PrevisioniPalina previsioni;

	/**
	 * Create a new BalloonOverlayView.
	 * 
	 * @param context - The activity context.
	 * @param balloonBottomOffset - The bottom padding (in pixels) to be applied
	 * when rendering this view.
	 */
	public BalloonOverlayView(Context context, int balloonBottomOffset) {

		super(context);
		setPadding(10, 0, 10, balloonBottomOffset);
		mDB = DatabaseService.getDatabaseServiceIstance(context);
		layout = new LinearLayout(context);
		layout.setVisibility(VISIBLE);
		
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.balloon_overlay, layout);
		title = (TextView) v.findViewById(R.id.balloon_item_title);
		snippet = (TextView) v.findViewById(R.id.balloon_item_snippet);
		star_check = (CheckBox)v.findViewById(R.id.stopStar_checkBox);
		speaker_button = (ImageView)v.findViewById(R.id.balloon_overlay_speakerButton);
		
		ImageView close = (ImageView) v.findViewById(R.id.close_img_button);
		close.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				TTS.getTTS().stopSpeak();
				layout.setVisibility(GONE);
			}
		});
		
		
		//Star button click listener
		star_check.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				CheckBox cb = (CheckBox) v;
				if(cb.isChecked()){
					if(mDB.insert_fermata_preferita(title.getText().toString()))
						UIUtils.popToastShort(v.getContext(), "Fermata " + title.getText() + " inserita nei preferiti!");
				}
				else
					if(mDB.delete_fermata_preferita(title.getText().toString()))
						UIUtils.popToastShort(v.getContext(), "Fermata " + title.getText() + " eliminata dai preferiti!");
					
			}
		}); 
		
		
		//Speaker button click listener
		speaker_button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				TTS.getTTS().speak(UIUtils.createTextToSpeech(previsioni));
			}
		}); 
		

		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.NO_GRAVITY;

		addView(layout, params);
		
		

	}
	
	
	
	
	/**
	 * Sets the view data from a given overlay item.
	 * 
	 * @param item - The overlay item containing the relevant view data 
	 * (title and snippet).
	 * 
	 * Handler per la risposta da parte di ANM 
	 * 0 tutt ok
	 * 1 errore 
	 */
	public void setData(Item item) {
		
		UIhandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				
				layout.setVisibility(VISIBLE);
				title.setVisibility(VISIBLE);
				snippet.setVisibility(VISIBLE);
				switch (msg.what) {
				case 0:
					if(mDB.isFermataPreferita(previsioni.getNum_fermata()))
						star_check.setChecked(true);
					
					if(previsioni.isPrevisioniDisponibili())
						speaker_button.setVisibility(VISIBLE);
					
					star_check.setVisibility(VISIBLE);
					title.setText(previsioni.getNum_fermata());
					snippet.setText(previsioni.toString());
					break;
				
				case 1:
					title.setText("Errore di connessione");
					snippet.setText("\nProblemi di connessione verifica la tua connessione internet:\n " + errorMessage);
					break;
				
				default:
					break;
				}
				
			       
			}
        	
        };
        new AnmBot(item.getSnippet()).start();
		
	}
	
	
	
	public class AnmBot extends Thread {

		private String palina;
		
		public AnmBot(String palina){
			this.palina = palina;
		}
		
		@Override
		public void run() {
			try {
				previsioni = AnmServices.getAnmServices().read_details_stop(palina);
				UIhandler.sendEmptyMessage(0);
			} catch (AnmServiceException e) {
				errorMessage = e.getMessage();
				UIhandler.sendEmptyMessage(1);
				
			}
		 		    
		}
		
	}
	

}
